package com.apps.shelper;

import com.apps.sexctption.DataException;
import com.apps.shelper.enums.ClassType;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Vector;

/**
 * 处理对象的属性字段
 */
public class FieldHelper {

    /**
     * 字段设置默认值
     * @param field
     * @param obj
     * @param valString
     * @param valNumber
     */
    public static void InitDefaultValue(Field field,Object obj,String valString,Integer valNumber)
    {
        if(null==field || null==obj)
            return;
        try {
            ClassType classType=ClassHelper.getClassType(field);
            switch (classType)
            {
                case NUMBER:
                    field.set(obj, valNumber);
                    break;
                case BIGDECIMAL:
                    field.set(obj, new BigDecimal(valNumber));
                    break;
                case BIGINTEGER:
                    field.set(obj, new BigInteger(valNumber.toString()));
                    break;
                case STRING:
                    field.set(obj, valString);
                    break;
                case ARRAYS:
                    field.set(obj, Array.newInstance(field.getType().getComponentType(), 0));
                    break;
                case LIST:
                    if(field.getType().isAssignableFrom(ArrayList.class)) {
                        field.set(obj, new ArrayList<>());
                        return;
                    }
                    if(field.getType().isAssignableFrom(LinkedList.class)) {
                        field.set(obj, new LinkedList<>());
                        return;
                    }
                    if(field.getType().isAssignableFrom(Vector.class)) {
                        field.set(obj, new Vector<>());
                        return;
                    }
                    if(field.getType().isAssignableFrom(Stack.class)) {
                        field.set(obj, new Stack<>());
                        return;
                    }
                    break;
                default:
                    throw new DataException("未知的类型"+field.getType().getName()+"无法设置默认值");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
